<?php
/**
 * Created by PhpStorm.
 * User: Edik
 * Date: 2016/3/5
 * Time: 16:50
 */

namespace Admin\Model;


use Think\Model;

class ServerModel extends Model
{
    protected $insertFields = array('title','server_type_id','homeimg','introduction','content');
    protected $updateFields = array('id','oldimg','title','server_type_id','homeimg','introduction','content');

    protected $_validate = array(

        array('title', 'require', '项目名称不能为空！', 1, 'regex', 3),
        array('title', '1,50', '项目名称的值最长不能超过 50 个字符！', 1, 'length', 3),
        array('introduction', 'require', '项目简介不能为空！', 1, 'regex', 3),
        array('introduction', '1,250', '项目简介不能超过250个字符！', 1, 'length', 3),
        array('content', 'require', '项目内容不能为空！', 1, 'regex', 3),

    );

    // 添加前
    protected function _before_insert(&$data, $option)
    {
        $data['user_id'] = session('a_id');
        $data['create_time'] = time();


        if(isset($_FILES['homeimg']) && $_FILES['homeimg']['error'] == 0)
        {
            $ret = uploadOne('homeimg', 'Server', array());
            if($ret['ok'] == 1)
            {
                $data['home_img'] = $ret['images'][0];
            }
            else
            {
                $this->error = $ret['error'];
                return FALSE;
            }
        }
    }

    // 修改前
    protected function _before_update(&$data, $option)
    {
        //修改人
        $data['edit_id'] = session('a_id');
        //修改时间
        $data['edit_time'] = time();

        //判断有没有重新上传图片
        if(isset($_FILES['homeimg']) && $_FILES['homeimg']['error'] == 0)
        {
            $ret = uploadOne('homeimg', 'Server', array());
            if($ret['ok'] == 1)
            {
                $data['home_img'] = $ret['images'][0];
            }
            else
            {
                $this->error = $ret['error'];
                return FALSE;
            }

            deleteImage(array(I('post.oldimg')));
        }
    }
}